#include"config.h"

#define LedSmat 0xfffffc03
#define Led_SCK (0x01<<17)
#define Led_SI (0x01<<18)
#define Led_RCK (0x01<<20)

const uint8 display_code[16]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
    0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
uint8 led_pit=0x00;
uint8 display_place;
uint8 led_buffer[8];
uint32 AD_num;

void LedInit(){
    PINSEL1 &= LedSmat;
    IO0DIR |= Led_SCK;
    IO0DIR |= Led_SI;
    IO0DIR |= Led_RCK;
}

void LedSend(uint8 code, uint8 place){
    uint16 data=0x0000;
    uint8 temp;
    data=place<<8;
    data=data|code;			//place*8+code
    
    IO0CLR =Led_RCK;
    for(temp=0;temp<16;temp++){
        IO0CLR=Led_SCK;
        if((data&0x8000)==0){
            IO0CLR=Led_SI;
        }
        else{
            IO0SET=Led_SI;
        }
        IO0SET=Led_SCK; 			//shift data one step left
        data=data<<1;			//shift next bit left for next step.
    }
    IO0SET=Led_RCK;			//take care of the last bit.
}

void LedPrint(uint32 data){
    /*  
        输入一个一个十六进制数，
        最长为8位，
        函数作用为将该数对应的编码放入缓冲数组
     */
    uint8 temp,code;
    for(temp=0;temp<8;temp++){
        code=data&0x0f;
        led_buffer[temp]=display_code[code];
        data=data>>4;
    }
}

void LedScan(){
    /* 
    每调用一次该函数，就会将缓冲数组里的一个字打印到LED上
     */
    display_place=~(0x80>>led_pit);
    LedSend(led_buffer[led_pit],display_place);
    led_pit++;
    if(led_pit==0x08){
        led_pit=0x00;
    }
}

void __irq IRQ_Time0Interrupt(){
    LedScan();
    T0IR=0x01;
    VICVectAddr=0x00;
}

void Time0_InterruptSet(){
    VICintSelect &= 0xffffffef;
    VICVectCntl2=0x24;
    VICVectAddr=(uint32)IRQ_Time0Interrupt;  //this line is important for enabling the irq.
    VICIntEnable=(0x01<<1);
}

void Time0_Init(){
    T0IR=0xff;
    T0TC=0;
    T0PR=0;
    T0MCR=0x03;
    T0MR0=Fpclk/1000;
    T0TCR=0x01;
    Time0_InterruptSet();
}

void __irq IRQ_ADInterrupt(){
    AD_num=ADDR;
    AD_num=AD_num>>6;
    AD_num=AD_num&0x000003ff;
    LedPrint(AD_num);
    VICVectAddr=0x00;
}

void AD_interruptInit(){
    VICintSelect &= 0xfffbffff;
    VICVectCntl3=0x32;
    VICVectAddr3=(uint32)IRQ_ADInterrupt;
    VICIntEnable=0x00040000;
}

void AD_Init(){
    PINSEL1 |= 0x00400000;
    ADCR=(1<<0)                 |
        ((Fpclk/1000000)<<8)    |
        (1<<16)                 |
        (2<<17)                 |
        (1<<21)                 |
        (0<<22)                 |
        (1<<24)                 |
        (0<<27);
    AD_interruptInit();
}

int main(){
    LedInit();
    AD_Init();
    Time0_Init();
    while(1);
    return 0;
}